package com.oneday.nuo.base.security.interceptor;

import cn.hutool.core.util.StrUtil;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.oneday.nuo.base.common.CommonStatic;
import com.oneday.nuo.base.common.RedisUtil;
import com.oneday.nuo.base.common.SpringUtil;
import com.oneday.nuo.base.exception.LoginException;
import com.oneday.nuo.base.exception.NuoException;
import com.oneday.nuo.base.response.NuoErrorStatus;
import com.oneday.nuo.base.security.jwt.JwtUtil;
import com.oneday.nuo.base.security.user.NuoUser;
import com.oneday.nuo.base.security.user.NuoUserDetailsService;
import com.oneday.nuo.base.tactics.token.TokenContext;
import com.oneday.nuo.base.tactics.token.TokenTactics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限过滤器
 * @Author: liushuai
 * @Date: 2021/2/10 10:21
 * @param : * @param null
 * @return :
 **/
@Component
public class NuoFilterSecurityInterceptor extends OncePerRequestFilter {

    @Value("${token.tokenType}")
    private String  tokenTactics;




    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String authorization =  httpServletRequest.getHeader("Authorization");
        String url = httpServletRequest.getRequestURI();
        if(StrUtil.isNotBlank(authorization)){
            //登录请求
            if(CommonStatic.LOGIN_URL.equals(url)){
                filterChain.doFilter(httpServletRequest,httpServletResponse);
            }
            NuoUser userDetails = NuoUser.builder().build();
            userDetails.setToken(authorization);
            TokenTactics tokenTacticsImpl = (TokenTactics) SpringUtil.getBean(tokenTactics);
            TokenContext tokenContext = new TokenContext(tokenTacticsImpl,userDetails);
            //验证token并设置返回用户
             userDetails = tokenContext.VerifyToken();
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
